﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;


namespace SiruEngine.Graphics
{
	/// <summary>
	/// 바닥을 표시하는 그리드 객체
	/// # 최대길이에 맞춰서 vertex buffer를 확보한다.
	/// # 가능하다면 출력 시 재조합을 하는 것도 좋을 듯.
	/// </summary>
	public class FloorTilePrimitive : GeometricPrimitive
	{
		public FloorTilePrimitive(GraphicsDevice graphicsDevice) : this(graphicsDevice, 30f, 1.0f, false)
		{
		}


		/// <summary>
		/// total_size는 전체 사이즈, tile_count는 한 변의 타일 수
		/// </summary>
		public FloorTilePrimitive(GraphicsDevice graphicsDevice, float total_size, float tile_size, bool is_solid)
		{
			Vector3 normal = new Vector3(0, 1, 0);

			if (is_solid)
			{
				// 전체 판
				float half_width = (total_size / 2);

				AddVertex(new Vector3(-half_width, 0, -half_width), normal);
				AddVertex(new Vector3(half_width, 0, -half_width), normal);
				AddVertex(new Vector3(-half_width, 0, half_width), normal);
				AddVertex(new Vector3(half_width, 0, half_width), normal);

				AddIndex(0);
				AddIndex(1);
				AddIndex(2);
				AddIndex(2);
				AddIndex(1);
				AddIndex(3);
			}
			else
			{
				int unit_count = (int ) (total_size / tile_size);
				int line_count = unit_count + 1;

				float half_floor = total_size / 2;
				float half_tile = tile_size / 2;

				// 타일
				for (int j = 0; j < line_count; ++j)
				{
					for (int i = 0; i < line_count; ++i)
					{
						float x = (float) i * tile_size;
						float y = (float) j * tile_size;

						AddVertex(new Vector3(x * tile_size - half_floor, 0, y * tile_size - half_floor), normal);
					}
				}

				int index = 0;

				for (int j = 0; j < unit_count; ++j)
				{
					for (int i = 0; i < unit_count; ++i)
					{
						bool bFlip = ((i + j) & 0x01) == 1;

						if (bFlip)
						{
							AddIndex(index);
							AddIndex(index + 1);
							AddIndex(index + line_count);

							AddIndex(index + line_count);
							AddIndex(index + 1);
							AddIndex(index + line_count + 1);

							bFlip = false;
						}
						else
						{
							bFlip = true;
						}

						index++;
					}

					index++;
				}
			}

			InitializePrimitive(graphicsDevice);
		}
	}
}
